package com.jzo2o.orders.manager.service.client;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jzo2o.api.market.CouponApi;
import com.jzo2o.api.market.dto.request.CouponUseReqDTO;
import com.jzo2o.api.market.dto.response.AvailableCouponsResDTO;
import com.jzo2o.api.market.dto.response.CouponUseResDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

@Slf4j
@Component
public class MarketClient {

    @Resource
    private CouponApi couponApi;

    @SentinelResource(value = "getAvailableCoupon",fallback = "getAvailableFallback",blockHandler = "getAvailableBlockHandler")
    public List<AvailableCouponsResDTO> getAvailableCoupon(BigDecimal totalAmount) {
        return couponApi.getAvailable(totalAmount);
    }

    public List<AvailableCouponsResDTO> getAvailableFallback(BigDecimal totalAmount,Throwable t) {
        log.error("远程调用market查询可用优惠券列表出现异常",t);
        return Collections.emptyList();
    }
    public List<AvailableCouponsResDTO> getAvailableFallback(BigDecimal totalAmount, BlockException b) {
        log.error("远程调用market查询可用优惠券列表被熔断降级",b);
        return Collections.emptyList();
    }

    @SentinelResource(value = "use",fallback = "useFallBack",blockHandler = "useCouponBlockHandler")
    public CouponUseResDTO use(CouponUseReqDTO dto) {
        return couponApi.use(dto);
    }

    public CouponUseResDTO useFallBack(CouponUseReqDTO dto,Throwable t) {
        log.error("远程调用market核销优惠券出现异常",t);
        return null;
    }
    public CouponUseResDTO useCouponBlockHandler(CouponUseReqDTO dto,BlockException b) {
        log.error("远程调用market核销优惠券被熔断降级",b);
        return null;
    }

    @SentinelResource(value = "useBack",fallback = "useBackFallBack",blockHandler = "useBackBlockHandler")
    public void useBack(Long orderId) {
        couponApi.useBack(orderId);
    }

    public void useBackFallBack(Long orderId,Throwable t) {
        log.error("远程调用market退回优惠券出现异常",t);
    }

    public void useBackBlockHandler(Long orderId,BlockException b) {
        log.error("远程调用market退回优惠券被熔断降级",b);
    }
}
